import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vamos/core/index.dart';
import '../../core/widgets/report_dialog.dart';
import 'social_detail_page.dart';
import '../publish/publish_page.dart';
import 'dart:math';

/// 社交动态列表界面
class VamosSocialListInterface extends StatefulWidget {
  const VamosSocialListInterface({super.key});

  @override
  State<VamosSocialListInterface> createState() =>
      _VamosSocialListInterfaceState();
}

class _VamosSocialListInterfaceState extends State<VamosSocialListInterface> {
  late ReduxSocialManager _socialManager;

  @override
  void initState() {
    super.initState();
    _socialManager = serviceLocator<ReduxSocialManager>();
  }

  /// 格式化发布时间
  String _formatPostTime(DateTime publishTime) {
    final hour = publishTime.hour.toString().padLeft(2, '0');
    final minute = publishTime.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  /// 生成随机浏览次数
  int _generateRandomViewCount() {
    final random = Random();
    return random.nextInt(500) + 50; // 50-549之间的随机数
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部固定标题栏
              _buildTopNavigationBar(),

              // 动态列表
              Expanded(child: _buildSocialPostsGrid()),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          Icon(
            Icons.arrow_back,
            color: Colors.white,
            size: 26.w,
          ).inkWell(onTap: () => Navigator.pop(context)),

          // 标题
          Expanded(
            child:
                Text('CIRCLE')
                    .fontSize(20.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w700,
                      ).fontFamily!,
                    )
                    .center(),
          ),

          // 发布按钮
          Image.asset(
            'assets/images/publish.png',
            width: 24.w,
            height: 24.w,
          ).inkWell(
            onTap: () {
              _navigateToPublish();
            },
          ),
        ],
      ),
    );
  }

  /// 构建社交动态网格
  Widget _buildSocialPostsGrid() {
    return StreamBuilder(
      stream: _socialManager.store.onChange,
      builder: (context, snapshot) {
        final posts = _socialManager.store.state.socialState.postCollection;

        if (posts.isEmpty) {
          return Center(
            child:
                Text(
                  'No posts available',
                ).fontSize(16.sp).textColor(Colors.grey[400]).center(),
          );
        }

        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: GridView.builder(
            padding: EdgeInsets.only(top: 8.h, bottom: 16.h),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 12.w,
              mainAxisSpacing: 16.h,
              childAspectRatio: 157 / 250,
            ),
            itemCount: posts.length,
            itemBuilder: (context, index) {
              return _buildSocialPostItem(posts[index]);
            },
          ),
        );
      },
    );
  }

  /// 构建单个社交动态项
  Widget _buildSocialPostItem(SocialPostEntity post) {
    final isImage =
        post.mediaType == PostMediaType.image && post.mediaUrl != null;
    final isVideo =
        post.mediaType == PostMediaType.video && post.thumbnailUrl != null;
    final viewCount = _generateRandomViewCount();

    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        color: Colors.white.withOpacity(0.1),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图片/视频区域
          Expanded(
            flex: 4,
            child: Padding(
              padding: EdgeInsets.all(5.w),
              child: Stack(
                children: [
                  // 媒体内容
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(12.r),
                        topRight: Radius.circular(12.r),
                      ),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(12.r),
                        topRight: Radius.circular(12.r),
                      ),
                      child:
                          isImage
                              ? Image.asset(
                                post.mediaUrl!,
                                width: double.infinity,
                                height: double.infinity,
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return Container(
                                    color: Colors.grey[800],
                                    child:
                                        Icon(
                                          Icons.image,
                                          size: 32.w,
                                          color: Colors.grey[600],
                                        ).center(),
                                  );
                                },
                              )
                              : isVideo
                              ? Image.asset(
                                post.thumbnailUrl!,
                                width: double.infinity,
                                height: double.infinity,
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return Container(
                                    color: Colors.grey[800],
                                    child:
                                        Icon(
                                          Icons.video_library,
                                          size: 32.w,
                                          color: Colors.grey[600],
                                        ).center(),
                                  );
                                },
                              )
                              : Container(
                                color: Colors.grey[800],
                                child:
                                    Icon(
                                      Icons.image,
                                      size: 32.w,
                                      color: Colors.grey[600],
                                    ).center(),
                              ),
                    ),
                  ),

                  // 视频播放图标
                  if (post.mediaType == PostMediaType.video)
                    SizedBox(
                      width: double.infinity,
                      height: double.infinity,
                      child:
                          Icon(
                            Icons.play_circle_filled,
                            size: 40.w,
                            color: Colors.white.withOpacity(0.9),
                          ).center(),
                    ),

                  // 右上角举报按钮
                  Positioned(
                    top: 8.h,
                    right: 8.w,
                    child: Container(
                      width: 24.w,
                      height: 24.w,
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.3),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.more_vert,
                        size: 16.w,
                        color: Colors.white,
                      ).center().inkWell(
                        onTap: () {
                          _handlePostReport(post);
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),

          // 文字信息区域
          Expanded(
            flex: 2,
            child: Padding(
              padding: EdgeInsets.all(8.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 动态文字（最多两行）
                  Expanded(
                    child: Text(
                      post.content,
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                        fontFamily:
                            GoogleFonts.poppins(
                              fontWeight: FontWeight.w400,
                            ).fontFamily,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),

                  SizedBox(height: 8.h),

                  // 时间和浏览次数
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // 时间
                      Text(
                        _formatPostTime(post.publishTime),
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.white.withOpacity(0.7),
                          fontFamily:
                              GoogleFonts.poppins(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                        ),
                      ),

                      // 浏览次数
                      Row(
                        children: [
                          Image.asset(
                            'assets/images/eye.png',
                            width: 16.w,
                            height: 16.w,
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            '$viewCount',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.white.withOpacity(0.7),
                              fontFamily:
                                  GoogleFonts.poppins(
                                    fontWeight: FontWeight.w400,
                                  ).fontFamily,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    ).inkWell(
      onTap: () {
        _navigateToSocialDetail(post);
      },
    );
  }

  /// 导航到社交动态详情页面
  void _navigateToSocialDetail(SocialPostEntity post) {
    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder:
            (context, animation, secondaryAnimation) =>
                VamosSocialDetailInterface(post: post),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(1.0, 0.0),
              end: Offset.zero,
            ).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeInOut),
            ),
            child: child,
          );
        },
        transitionDuration: Duration(milliseconds: 300),
      ),
    );
  }

  /// 处理动态举报
  void _handlePostReport(SocialPostEntity post) {
    showVamosReportDialog(
      context: context,
      title: 'Report Post',
      subtitle: 'Please select a reason for reporting this post.',
      onReportSubmitted: (VamosReportOption option) {
        _deletePostAndExit(post);
      },
    );
  }

  /// 删除动态并返回
  void _deletePostAndExit(SocialPostEntity post) async {
    try {
      final success = await _socialManager.deletePost(post.postId);
      if (success) {
        NotificationUtils.showSuccess(
          context,
          message: 'You won\'t see this again.',
        );
        // 不需要返回，因为列表会自动更新
      } else {
        NotificationUtils.showError(context, message: 'Failed to report post.');
      }
    } catch (e) {
      NotificationUtils.showError(context, message: 'Error reporting post: $e');
    }
  }

  /// 导航到发布页面
  void _navigateToPublish() {
    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder:
            (context, animation, secondaryAnimation) =>
                VamosPublishInterface(initialTabIndex: 1),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(1.0, 0.0),
              end: Offset.zero,
            ).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeInOut),
            ),
            child: child,
          );
        },
        transitionDuration: Duration(milliseconds: 300),
      ),
    );
  }
}
